import { DxmState, ShipmentLimitSecond } from '@/lib/dianxiaomi';
import { generateRandomId } from '@/lib/utils';
import { Draft } from 'immer';
import { create } from 'zustand';
import { persist, PersistStorage, redux, StorageValue } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { name } from '../package.json';

const SETTINGSKEY = 'CLSTools-' + name;
export const settingsStorage = storage.defineItem<StorageValue<State>>(`local:${SETTINGSKEY}`);

export enum Status {
  STOP,
  RUNNING,
}

export interface AccountSetting {
  giga: {
    clientId: string;
    clientSecret: string;
    accessToken: string;
    tokenType: string;
  };
  volcengine: {
    apiKey: string;
  };
}

export interface GigaSettings {
  // 最少库存量
  minAvailable: number;

  // 是否在筛选时进行批量采集
  hasCollectFilterPage: boolean;

  // 筛选的配置
  filter: {
    // 是否采集已采集的
    qty_min: string;

    // 是否采集已下载的
    skip_has_downloaded: boolean;

    // 是否采集已购买
    skip_has_purchased: boolean;

    // 是否采集已收藏
    skip_has_wishlist: boolean;

    // 是否是 LTL 的运算方式
    is_ltl: boolean;
  };
}

export interface CategoryItem {
  id: string;
  categoryId: number | '';
  categoryName: string;
  attributes: string;
}

export interface BackgroundReference {
  id: string;
  dataUrl: string;
}

const defaultState = {
  status: Status.RUNNING,
  baseSettings: {
    isDefaultOpenCollect: false,
    // 每隔多次事件清理记录的信息
    clearMessageInterval: 1800,
  },
  batchSettings: {
    // 下载时的并发数量请求数量
    taskConcurrencyLimit: 6,

    // 是否在页面启动时执行上次任务
    isResumeTask: false,
  },
  pushSettings: {
    isUploadToImageSpace: false,
    shopId: '',
    dxmState: DxmState.offline,
    categoryOptionList: [
      {
        id: generateRandomId(),
        categoryId: '' as '',
        categoryName: '',
        attributes: '',
      },
    ],
    category: {
      id: generateRandomId(),
      categoryId: '' as '',
      categoryName: '',
      attributes: '',
    },
    isUseAiCategory: true,
    productOrigin: 'CN',
    region2Id: '43000000000006',
    shipmentLimitSecond: ShipmentLimitSecond['2个工作日内发货'],
    warehouseId: 'WH-09092282531990900',
    freightTemplateId: 'HFT-11640433187717260900',
    priceMultiplyingFactor: 2,
    commonProductInstructions: '',
  },
  publicSettings: {
    publicInterval: 3000,
  },
  processSettings: {
    generatorTitleName: '床',
    isUseAiGenerateTitle: true,
    allowCharacters: '',
    hotSearch: '',
    violateList: [],
    isRemoveViolateList: true,
    bannerWorldList: [],
    isRemoveBannerWorldList: true,
    isRemoveImageInProcess: true,
    comfyUILink: 'https://44ey21fgjup5fc8m-80.container.x-gpu.com/',
    comfyUIFilesLink: 'https://44ey21fgjup5fc8m-8081.container.x-gpu.com/',
    comfyUIInputImageNodeId: 62,
    comfyUIInputBackgroundImageNodeId: 84,
    comfyUIOutputImageNodeId: 261,
    isUseAiProcessScenceAndWhiteImages: false,
    isFilterProcessScenceAndWhiteImages: false,
    aiProcessTimeout: 480,
    aiRetryTime: 3,
    isUseProcessSpliceImage: false,
    backgroundReferenceList: [],
    aiTendency: {
      min: 0,
      max: 0.8,
    },
    aiCreative: {
      min: 8,
      max: 13,
    },
    aiSamplingStep: {
      min: 20,
      max: 28,
    },
    maskRatio: {
      min: 0.85,
      max: 0.95,
    },
    spliceBackgroundReferenceList: [],
    spliceMargin: 20,
    spliceGap: 20,
    spliceRadiu: 15,
  },
  accountSetting: {
    giga: {
      clientId: '20298409_USA_release',
      clientSecret: '317a9d5da3ac439ab502c760d1d858a2',
      accessToken: '',
      tokenType: 'bearer',
    },
    volcengine: {
      apiKey: '',
    },
  },
  uploadStatistics: {
    success: 0,
    error: 0,
  },
  resourceStatistics: {
    success: 0,
    error: 0,
  },
  gigaSettings: {
    minAvailable: 10,
    hasCollectFilterPage: true,
    filter: {
      qty_min: '10',
      skip_has_downloaded: false,
      skip_has_purchased: false,
      skip_has_wishlist: false,
      is_ltl: false,
    },
  },
};

export interface State {
  status: Status;
  baseSettings: {
    isDefaultOpenCollect: boolean;
    clearMessageInterval: number;
  };
  batchSettings: {
    // 下载时的并发数量请求数量
    taskConcurrencyLimit: number;

    // 是否在页面启动时执行上次任务
    isResumeTask: boolean;
  };
  pushSettings: {
    isUploadToImageSpace: boolean;
    shopId: string;
    dxmState: DxmState;
    categoryOptionList: CategoryItem[];
    category: CategoryItem;
    // 是否不使用 ai 进行分类
    isUseAiCategory: boolean;
    productOrigin: string;
    region2Id: string;
    shipmentLimitSecond: ShipmentLimitSecond;
    warehouseId: string;
    freightTemplateId: string;
    priceMultiplyingFactor: number;
    commonProductInstructions: string;
  };
  publicSettings: {
    publicInterval: number;
  };
  processSettings: {
    generatorTitleName: string;
    isUseAiGenerateTitle: boolean;
    allowCharacters: string;
    hotSearch: string;
    violateList: string[];
    isRemoveViolateList: boolean;
    // 品牌词列表
    bannerWorldList: string[];
    isRemoveBannerWorldList: boolean;
    // 是否在加工图片前删除轮播图中的图片
    isRemoveImageInProcess: boolean;
    // comfyUI 的服务器地址
    comfyUILink: string;
    comfyUIFilesLink: string;
    comfyUIInputImageNodeId: number;
    comfyUIInputBackgroundImageNodeId: number;
    comfyUIOutputImageNodeId: number;
    // 是否对场景图和白底图进行 ai 加工
    isUseAiProcessScenceAndWhiteImages: boolean;
    // 是否对场景图和白底图进行滤镜处理
    isFilterProcessScenceAndWhiteImages: boolean;
    aiProcessTimeout: number;
    // ai 加工图片时的重试次数
    aiRetryTime: number;
    // 是否对细节图行加工
    isUseProcessSpliceImage: boolean;
    backgroundReferenceList: BackgroundReference[];
    aiTendency: {
      min: number;
      max: number;
    };
    aiCreative: {
      min: number;
      max: number;
    };
    aiSamplingStep: {
      min: number;
      max: number;
    };
    maskRatio: {
      min: number;
      max: number;
    };
    spliceBackgroundReferenceList: BackgroundReference[];
    spliceMargin: number;
    spliceGap: number;
    spliceRadiu: number;
  };
  accountSetting: AccountSetting;
  uploadStatistics: {
    success: number;
    error: number;
  };
  resourceStatistics: {
    success: number;
    error: number;
  };
  gigaSettings: GigaSettings;
}

type Actions =
  | {
      type: 'reset';
    }
  | {
      type: 'update';
      update: (draftState: Draft<State>) => void;
    };

const persistStorage: PersistStorage<State> = {
  getItem: async () => {
    const state = await settingsStorage.getValue();
    if (!state) {
      return {
        state: defaultState,
        version: 0,
      };
    }
    return state;
  },
  setItem: async (key, newValue) => {
    await settingsStorage.setValue(newValue);
  },
  removeItem: (): void => {
    settingsStorage.removeValue();
  },
};

const reducer = (state: Draft<State>, action: Actions) => {
  if (action.type === 'reset') {
    return defaultState;
  }
  if (action.type === 'update') {
    const update = action.update;
    update(state);
  }
};

export const useSettingsStore = create(
  // @ts-expect-error 因为 immer 导致了 reducer 可以返回 undefiend
  persist(immer(redux(reducer, defaultState)), {
    name: SETTINGSKEY,
    storage: persistStorage,
  }),
);
